<template>
  <div class="central_lab_wrapper">
    <div class="main_page">
      <div class="search_part">
        <el-upload
          action
          style="margin-left: 8px"
          :http-request="handleImportEmbeddedEncoding"
          :file-list="fileList"
          :show-file-list="false"
        >
          <el-button type="primary" size="mini" :loading="importLoading" style="margin-right: 8px"> 导入 </el-button>
        </el-upload>
        <el-button type="primary" size="mini" @click="handleDownLoadData()">导出</el-button>
        <el-button type="primary" size="mini" @click="handleDownLoad()">下载导入模板</el-button>
      </div>
      <div class="table_part">
        <el-table :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }" :stripe="true" :data="tableData">
          <el-table-column label="#" align="center" width="50" type="index"></el-table-column>
          <el-table-column align="center" prop="coreCode" label="中心编号"> </el-table-column>
          <el-table-column align="center" prop="coreName" label="中心名称"></el-table-column>
          <el-table-column align="center" prop="labList" label="实验室">
            <template v-slot="{ row }">
              <div v-for="item in row.labList" :key="item.id">{{ item.labName }}({{ item.labCode }})</div>
              <i style="color: #409eff" class="el-icon-plus" @click="handleAddSth(row)"></i>
            </template>
          </el-table-column>
          <el-table-column align="cemter" prop="labList">
            <template v-slot="{ row }">
              <div v-for="item in row.labList" :key="item.id">
                <i @click="handleEdit(item)" class="el-icon-edit" style="margin-right: 12px"></i>
                <i @click="handleDelete(item)" class="el-icon-delete" style="color: red; margin-right: 12px"></i>
                <span @click="handleClickOcr(item)" style="color: #409eff">OCR</span>
              </div>
              <span></span>
            </template>
          </el-table-column>
        </el-table>
        <el-row style="margin-top: 12px" type="flex" justify="end">
          <el-pagination
            layout="total,sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageParams.pageNo"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageParams.pageSize"
            :total="pageParams.total"
          >
          </el-pagination>
        </el-row>
      </div>
    </div>
    <!-- 新增和编辑弹窗 -->
    <el-dialog :visible="addDiaVis" title="新增实验室" width="500px" @close="handleCancel()">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
        <el-form-item v-for="item in formColumns" :key="item.prop" :label="item.label" :prop="item.prop">
          <el-input style="width: 85%" size="mini" v-model="formData[item.prop]"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="handleCancel()">取消</el-button>
        <el-button type="primary" size="mini" @click="handleSubmit()">提交</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible="ocrVis" title="OCR对照列配置" width="500px" @close="handleCancelOcr()">
      <el-form ref="formRefOcr" :model="formDataOcr" :rules="formRulesOcr" label-width="210px">
        <el-form-item v-for="item in formColumnsOcr" :key="item.prop" :label="item.label" :prop="item.prop">
          <el-input
            size="mini"
            style="width: 90%"
            v-if="item.ele === 'input'"
            v-model="formDataOcr[item.prop]"
            :placeholder="item.placeholder"
          ></el-input>
          <el-select
            size="mini"
            style="width: 90%"
            v-if="item.ele === 'select'"
            v-model="formDataOcr[item.prop]"
            :placeholder="item.placeholder"
          >
            <el-option v-for="it in item.options" :key="it.value" :label="it.label" :value="it.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="handleCancelOcr()">取消</el-button>
        <el-button type="primary" size="mini" @click="btnSubmitOcr()">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { handleExportResponse } from '@/utils/index'
export default {
  name: 'central-lab',
  data() {
    return {
      pageParams: {
        pageNo: 1,
        pageSize: 10,
        total: 100,
      },
      addDiaVis: false,
      formColumns: [
        { ele: 'input', label: '实验室名称：', prop: 'labName' },
        { ele: 'input', label: '实验室编号：', prop: 'labCode' },
      ],
      formData: {
        labCode: '',
        labName: '',
      },
      formRules: {
        labCode: [{ required: true, message: '请填写', trigger: 'blur' }],
        labName: [{ required: true, message: '请填写', trigger: 'blur' }],
      },
      tableData: [],
      editId: '',
      coreId: '',
      isAdd: true,
      ocrVis: false,
      formColumnsOcr: [
        { ele: 'input', label: '检查项所在列：', prop: 'referRowCh', placeholder: 'OCR图片中：检查所在列' },
        {
          ele: 'select',
          label: '检查项与缩写同列的混合样式：',
          prop: 'referRowStyle',
          options: [
            { label: '检查项(缩写)', value: '检查项(缩写)' },
            { label: '缩写(检查项)', value: '缩写(检查项)' },
          ],
          placeholder: '如：检查项(缩写)',
        },
        { ele: 'input', label: '单位所在列：', prop: 'referRowEn', placeholder: 'OCR图片中：检查项单位所在列' },
        { ele: 'input', label: '检查结果所在列：', prop: 'resultRow', placeholder: 'OCR图片中：检查结果所在列' },
      ],
      formDataOcr: {
        referRowCh: '',
        referRowStyle: '',
        referRowEn: '',
        resultRow: '',
      },
      formRulesOcr: {
        referRowCh: [
          {
            required: true,
            message: '请填写',
            trigger: 'blur',
          },
        ],
        referRowStyle: [
          {
            required: true,
            message: '请选择',
            trigger: 'blur',
          },
        ],
        referRowEn: [
          {
            required: true,
            message: '请填写',
            trigger: 'blur',
          },
        ],
        resultRow: [
          {
            required: true,
            message: '请填写',
            trigger: 'blur',
          },
        ],
      },
      projectId: '',
      projectDatabaseId: '',
      importLoading: false,
      fileList: [],
    }
  },
  created() {
    this.projectId = localStorage.getItem('sys-project-id') || ''
    this.projectDatabaseId = localStorage.getItem('project-database-Id') || ''
    this.getCentralLab()
  },
  methods: {
    ...mapActions('centralManagement', [
      'getCentralLabAPI',
      'addCentralLabAPI',
      'editCentralLabAPI',
      'deleteCentralLabAPI',
      'downloadTemplateCentralLabAPI',
      'exportAPI',
      'importCoreLabAPI',
    ]),
    // 导入
    handleImportEmbeddedEncoding(file) {
      this.importLoading = true
      const formData = new FormData()
      formData.append('file', file.file)
      formData.append('projectId', this.projectId)
      formData.append('projectDatabaseId', this.projectDatabaseId)
      // 导入请求
      this.importCoreLabAPI({ data: formData })
        .then(res => {
          this.importLoading = false
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '导入成功' + res.message,
            })
            this.fileList.push({ name: file.file.name, url: res.data })
            // 获取表格数据
            this.getCentralLab()
          } else {
            this.$message({
              type: 'error',
              message: '导入数据失败，请稍后重试~',
            })
          }
        })
        .catch(error => {
          this.$message.error(error)
        })
    },

    // 导出
    handleDownLoadData() {
      const data = {
        projectDatabaseId: this.projectDatabaseId,
        projectId: this.projectId,
      }
      this.exportAPI({ data }).then(res => {
        const { data } = res
        handleExportResponse(data, '中心实验室_列表')
      })
    },

    // 下载导入模板
    handleDownLoad() {
      this.downloadTemplateCentralLabAPI().then(res => {
        const { data } = res
        handleExportResponse(data, '中心实验室_导入模板')
      })
    },
    // 获取表格数据
    async getCentralLab() {
      const params = {
        ...this.pageParams,
        projectId: this.projectId,
        projectDatabaseId: this.projectDatabaseId,
      }
      const res = await this.getCentralLabAPI({ params })
      if (res.code === 200) {
        res.data.records.sort((a, b) => a.coreCode - b.coreCode)
        this.tableData = res.data.records
        this.pageParams.total = res.data.total
      }
    },
    // 页面尺寸改变
    handleSizeChange(val) {
      this.pageParams.pageSize = val
      this.getCentralLab()
    },
    // 页面改变
    handleCurrentChange(val) {
      this.pageParams.pageNo = val
      this.getCentralLab()
    },
    // 点击加号
    handleAddSth(row) {
      this.isAdd = true
      this.coreId = row.id
      this.addDiaVis = true
    },
    // 点击编辑
    handleEdit(item) {
      this.isAdd = false
      this.formData.labCode = item.labCode
      this.formData.labName = item.labName
      this.formData.id = item.id
      this.addDiaVis = true
    },
    // 点击删除
    async handleDelete(item) {
      const params = {
        id: item.id,
      }
      const res = await this.deleteCentralLabAPI({
        params,
      })
      if (res.code === 200) {
        this.$message.success('删除成功')
        this.getCentralLab()
      }
    },
    handleClickOcr(item) {
      this.ocrVis = true
      this.formDataOcr.id = item.id
      this.formDataOcr.referRowCh = item.referRowCh
      this.formDataOcr.referRowStyle = item.referRowStyle
      this.formDataOcr.referRowEn = item.referRowEn
      this.formDataOcr.resultRow = item.resultRow
    },
    // 公共删除
    publicClose() {
      this.addDiaVis = false
      this.$refs.formRef.resetFields()
      this.formData.labCode = ''
      this.formData.labName = ''
      this.formData.id = ''
    },
    // 点击取消
    handleCancel() {
      this.publicClose()
    },
    // 点击提交
    async handleSubmit() {
      await this.$refs.formRef.validate()
      if (this.isAdd) {
        const data = {
          ...this.formData,
          projectId: this.projectId,
          projectDatabaseId: this.projectDatabaseId,
          coreId: this.coreId,
        }
        const res = await this.addCentralLabAPI({ data })
        if (res.code === 200) {
          this.$message.success('新增成功！')
          this.getCentralLab()
          this.publicClose()
        }
      } else {
        const data = { ...this.formData }
        const res = await this.editCentralLabAPI({ data })
        if (res.code === 200) {
          this.$message.success('修改成功')
          this.getCentralLab()
          this.publicClose()
        }
      }
    },
    publicCloseOcr() {
      this.ocrVis = false
      this.$refs.formRefOcr.resetFields()
      this.formDataOcr.referRowCh = ''
      this.formDataOcr.referRowStyle = ''
      this.formDataOcr.referRowEn = ''
      this.formDataOcr.resultRow = ''
    },
    handleCancelOcr() {
      this.publicCloseOcr()
    },
    async btnSubmitOcr() {
      this.$refs.formRefOcr.validate()
      const data = {
        ...this.formDataOcr,
      }
      const res = await this.editCentralLabAPI({
        data,
      })
      if (res.code === 200) {
        this.$message.success('设置成功')
        this.getCentralLab()
        this.publicCloseOcr()
      }
    },
    btnImport() {
      this.$message.warning('功能开发中！')
    },
    btnExport() {
      this.$message.warning('功能开发中！')
    },
    btnDownload() {
      this.$message.warning('功能开发中！')
    },
  },
}
</script>

<style lang="scss" scoped>
.central_lab_wrapper {
  background-color: $white;
  height: calc(100% - 24px);
  padding: 12px;
  .search_part {
    margin-bottom: 12px;
    display: flex;
  }
}
</style>
